// 手写resolve------aliases 插件

// 创建vite插件在原有的基础上修改 vite会自动覆盖
import fs from "fs";
import path from "path";

// 判断是否为文件夹还是文件
function diffDirOrFile(result = [], basePath = "../src") {
  let resolveResult = {
    dir: [],
    file: [],
  };
  result.forEach((name) => {
    let state = fs.statSync(path.resolve(__dirname, basePath, name));
    if (state.isDirectory()) {
      resolveResult.dir.push(name);
    } else {
      resolveResult.file.push(name);
    }
  });
  return resolveResult;
}
// 拿到所有src下的文件
function getTotalSrcDir(keyName) {
  let obj = {};
  const dir = fs.readdirSync(path.resolve(__dirname, "../src"));
  const resolveResult = diffDirOrFile(dir);
  resolveResult.dir.forEach((name) => {
    obj[`${keyName}${name}`] = path.resolve(__dirname, "../src" + "/" + name);
    obj[`${keyName}`] = path.resolve(__dirname, "../src");
  });

  return obj;
}
module.exports = ({ keyName = "@" } = {}) => {
  return {
    //参数与export default defineConfig((zks) => {zks参数一致
    // mode: 'development',
    // command: 'serve'  |build,   //开发
    // isSsrBuild: false,
    // isPreview: false
    config(config, env) {
      // console.log(config,env);
      const res = getTotalSrcDir(keyName);
      return {
        // envPrefix: "EWin",
        resolve: {
          alias: res,
        },
      };
    },
  };
};
